<template>
  <div style="padding: 10px">
    <!--    功能区域-->
    <div style="margin: 10px 0">
      <el-button type="primary" @click="addMember">新增会员</el-button>
      <el-popconfirm style="margin: 10px 10px" title="确定删除吗？" @onConfirm="selectDelete">
        <template #reference>
          <el-button type="primary">删除选中</el-button>
        </template>
      </el-popconfirm>
      <el-button type="primary" @click="exportExcel">导出Excel</el-button>
    </div>
    <!--    搜索区域-->
    <div style="margin: 10px 0">
      <el-input v-model="search" placeholder="请输入关键字查询" style="width: 40%;background-color: #fff">
        <el-select slot="prepend" v-model="select" placeholder="请选择" style="width: 120px">
          <el-option label="会员名称" value="memberName" />
          <el-option label="手机号" value="phoneNumber" />
        </el-select>
        <el-button slot="append" icon="el-icon-search" @click="inquire" />
      </el-input>
    </div>
    <!--    表格区域-->
    <el-table
      ref="multipleTable"
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      border
      stripe
      :header-cell-style="headClass"
      :cell-style="rowClass"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="序号"
        type="index"
        :index="indexMethod"
        sortable
      />
      <el-table-column
        prop="memberName"
        label="会员名称"
      />
      <el-table-column
        prop="phoneNumber"
        label="手机号"
      />
      <el-table-column
        prop="birthday"
        label="生日"
        :formatter="formatDate"
        sortable
      />
      <el-table-column
        prop="balance"
        label="余额"
        sortable
      />
      <el-table-column
        prop="remark"
        label="备注"
      />
      <el-table-column label="操作" width="140">
        <template #default="scope">
          <el-button type="primary" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确定删除吗？" @onConfirm="handleDelete(scope.row.id)">
            <template #reference>
              <el-button style="margin-left: 5px" size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <div style="margin: 10px 0">
      <el-pagination
        :current-page="currentPage"
        :page-sizes="pageSizes"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!--    增加会员弹窗-->
    <el-dialog
      title="添加会员"
      :visible.sync="addMemberVisible"
      width="30%"
      center
      :show-close="false"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="120px">
        <el-form-item
          label="会员名称"
          prop="memberName"
          :rules="{required: true, message: '会员名称不能为空', trigger: 'blur'}"
        >
          <el-input v-model="form.memberName" style="width: 80%" />
        </el-form-item>
        <el-form-item
          label="手机号"
          prop="phoneNumber"
        >
          <el-input v-model="form.phoneNumber" type="phoneNumber" autocomplete="off" style="width: 80%" />
        </el-form-item>
        <el-form-item
          v-show="form.id"
          label="余额"
          prop="balance"
        >
          <el-input v-model="form.balance" type="number" autocomplete="off" style="width: 80%" />
        </el-form-item>
        <el-form-item
          label="生日"
          prop="birthday"
        >
          <el-date-picker
            v-model="form.birthday"
            style="width: 80%"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
            :editable="true"
          />
        </el-form-item>
        <el-form-item
          label="备注"
          prop="remark"
        >
          <el-input v-model="form.remark" type="textarea" :rows="3" style="width: 80%" />
        </el-form-item>
        <div style="margin-top: 50px;text-align: center">
          <el-button style="margin-right: 20px" size="big" @click="cancel">取 消</el-button>
          <el-button style="margin-left: 20px" size="big" type="primary" @click="submitForm('form')">确 定</el-button>
        </div>
      </el-form>

    </el-dialog>
  </div>
</template>

<script>

import { Message } from '_element-ui@2.13.2@element-ui'
import { parseTime } from '@/utils'
import { addMember, deleteById, selectMember, update } from '@/api/registerMember'

export default {
  name: 'RegisterMember',
  data() {
    return {
      // 表单校验
      rules: {
        phoneNumber: [
          {
            required: true, message: '请输入联系方式', trigger: 'blur' },
          {
            min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/,
            message: '请输入正确的手机号码'
          }
        ]
      },
      // 添加会员表格
      form: {},
      // 添加会员弹窗,默认关闭
      addMemberVisible: false,
      // 每页查看数量
      pageSizes: [10, 20, 50, 200],
      // 每页显示数量
      pageSize: 10,
      // 总数量
      total: 0,
      // 当前页
      currentPage: 1,
      // 查询输入框
      search: '',
      // 查询选择项目
      select: 'memberName',
      // 表格数据
      tableData: [],
      // 选中数据
      multipleSelection: []
    }
  },
  mounted() {
    // 默认加载根据会员名称查询
    this.selectPage(this.currentPage, this.pageSize)
  },
  methods: {
    // 导出Excel 工具
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 导出Excel
    exportExcel() {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['会员名称', '手机号', '生日', '余额', '备注']
        const filterVal = ['memberName', 'phoneNumber', 'birthday', 'balance', 'remark']
        const list = this.tableData
        const data = this.formatJson(filterVal, list)
        excel.export_json_to_excel({
          header: tHeader, // 表头 必填
          data, // 具体数据 必填
          filename: '会员数据', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 页码跟序号处理 工具
    indexMethod(index) {
      const currentPage = this.currentPage // 当前页码
      const pageSize = this.pageSize // 每页条数
      return index + 1 + (currentPage - 1) * pageSize // 返回表格序号
    },
    // 日期处理 工具
    formatDate(row, column) {
      // 获取单元格数据
      const data = row[column.property]
      if (data == null) {
        return null
      }
      const dt = new Date(data)
      return dt.getFullYear() + '-' + (dt.getMonth() + 1) + '-' + dt.getDate()
    },
    // 点击查询
    inquire() {
      // 调用查询方法
      this.selectPage(this.currentPage, this.pageSize)
    },
    // 查询代码抽取 工具
    selectPage(currentPage, pageSize) {
      new Promise((resolve, reject) => {
        // 查询请求
        selectMember(currentPage, pageSize, this.search, this.select).then(res => {
          // 赋值给页面渲染
          this.tableData = res.data.records
          // 赋值总数
          this.total = res.data.total
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 新增取消
    cancel() {
      this.addMemberVisible = false
      this.form = {}
    },
    // 提交
    submitForm(form) {
      if (this.form.id) {
        // 修改
        new Promise((resolve, reject) => {
          update(this.form).then(response => {
            if (response.code === 20000) {
              Message({
                message: '修改成功!',
                type: 'success',
                duration: 3 * 1000
              })
            }
            // 关闭新增窗口
            this.addMemberVisible = false
            // 刷新数据页面,否则乐观锁会锁死
            this.selectPage(this.currentPage, this.pageSize)
            // 清空上传组件数据
            this.form = {}
            resolve()
          }).catch(error => {
            reject(error)
          })
        })
      } else {
        // 新增
        this.$refs[form].validate((valid) => {
          if (valid) {
            new Promise((resolve, reject) => {
              addMember(this.form).then(response => {
                if (response.code === 20000) {
                  Message({
                    message: '添加成功!',
                    type: 'success',
                    duration: 3 * 1000
                  })
                }
                // 刷新数据页面
                this.selectPage(this.currentPage, this.pageSize)
                // 关闭新增窗口
                this.addMemberVisible = false
                // 清空上传组件数据
                this.form = {}
                resolve()
              }).catch(error => {
                reject(error)
              })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    // 点击新增按钮
    addMember() {
      // 打开新增视图
      this.addMemberVisible = true
    },
    // 改变每页显示条数触发
    handleSizeChange(val) {
      this.pageSize = val
      this.selectPage(this.currentPage, val)
    },
    // 改变当前页码触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.selectPage(val, this.pageSize)
    },
    // 表头居中显示
    headClass() {
      return 'text-align:center'
    },
    // 表格数据居中显示
    rowClass() {
      return 'text-align:center'
    },
    // 全选或全不选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 编辑按钮
    handleEdit(row) {
      // 打开新增窗口,改变为编辑
      this.addMemberVisible = true
      // 赋值编辑窗口
      this.form = row
    },
    // 删除按钮
    handleDelete(id) {
      new Promise((resolve, reject) => {
        deleteById(id).then(response => {
          if (response.code === 20000) {
            Message({
              message: '删除成功!',
              type: 'success',
              duration: 3 * 1000
            })
          }
          // 刷新数据页面
          this.selectPage(this.currentPage, this.pageSize)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 选中删除
    selectDelete() {
      for (const multipleSelection of this.multipleSelection) {
        this.handleDelete(multipleSelection.id)
      }
    }
  }
}
</script>

<style scoped>
</style>
